<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <el-card>
        <el-form :inline="true" class="demo-form-inline queryForm">
            <el-form-item label="用户名：">
                <el-input v-model="username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="用户昵称：">
                <el-input v-model="name" placeholder="请输入用户昵称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="getUserList">搜索</el-button>
                <el-button icon="Refresh" @click="resetUser">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin-top: 10px;">
        <div class="opreation">
            <el-button type="primary" icon="Plus" @click="dialogVisible = true;">添加角色</el-button>
            <el-button type="danger" icon="Delete" @click="removeMoreUser">批量删除</el-button>
        </div>
        <div class="table">
            <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50" align="center"/>
                <el-table-column label="#" width="50" align="center">
                    <template #default="scope">{{ scope.$index+1 }}</template>
                </el-table-column>
                <el-table-column label="id" prop="id" width="100" align="center"></el-table-column>
                <el-table-column label="用户名" prop="username" align="center"></el-table-column>
                <el-table-column label="用户昵称" prop="name" align="center"></el-table-column>
                <el-table-column label="用户角色" prop="roleName" align="center" width="250" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="createTime" align="center"></el-table-column>
                <el-table-column label="更新时间" prop="updateTime" align="center"></el-table-column>
                <el-table-column label="操作" prop="" width="400" align="center">
                    <template #default="scope">
                        <el-button type="primary" size="mini" icon="User" @click="fpRole(scope.row.id)">分配角色</el-button>
                        <el-button type="warning" size="mini" icon="Edit" @click="editUser(scope.row.id)">编辑</el-button>
                        <el-popconfirm :title="`是否确认删除用户【${scope.row?.username||''}】?`" width="250px" icon="Delete" @confirm="confirmDelete(scope.row.id)">
                            <template #reference>
                                <el-button type="danger" size="mini" icon="Delete">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[5, 10, 20, 30, 50, 100]"
                    :total
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </div>
    </el-card>
    <el-dialog 
        v-model="dialogVisible"
        :title="userDto.id?'编辑用户':'新增用户'" 
        width="600"
        @closed="initReset"
    >
        <el-form
            ref="userDtoRef"
            :model="userDto"
            :rules="userRules"
            label-width="auto"
            class="demo-ruleForm"
        >
            <el-form-item label="用户名" prop="username">
                <el-input v-model="userDto.username" />
            </el-form-item>
            <el-form-item label="用户昵称" prop="name">
                <el-input v-model="userDto.name" />
            </el-form-item>
            <el-form-item label="用户密码" prop="password_cs" v-if="!userDto.id">
                <el-input type="password" v-model="userDto.password_cs" show-password/>
            </el-form-item>
            <el-form-item label="确认密码" prop="password" v-if="!userDto.id">
                <el-input type="password" v-model="userDto.password" show-password/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmAdd">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <el-drawer v-model="userDrawer" direction="rtl">
        <template #header>
            <h2>分配角色</h2>
        </template>
        <template #default>
            <el-form label-width="auto">
                <el-form-item label="用户名">
                    <el-input v-model="userDto.username" disabled />
                </el-form-item>
                <el-form-item label="用户昵称">
                    <el-input v-model="userDto.name" disabled />
                </el-form-item>
                <el-form-item label="角色列表" class="roleList">
                    <el-checkbox
                        v-model="checkAll"
                        :indeterminate="isIndeterminate"
                        @change="handleCheckAllChange"
                    >全选</el-checkbox>
                    <el-checkbox-group
                        v-model="roleIdList"
                        @change="handleCheckedCitiesChange"
                    >
                        <el-checkbox v-for="role in roleList" :key="role.id" :label="role.roleName" :value="role.id">
                        {{ role.roleName }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancelDrawer">取消</el-button>
                <el-button type="primary" @click="confirmDrawer">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script lang="ts" setup>
    import { ref, reactive, onMounted, nextTick } from "vue";
    import { ElMessage } from "element-plus";
    import userApi from "@/api/acl/user";

    let username = ref("");
    let name = ref("");
    let currentPage = ref(1);
    let pageSize = ref(10);
    let total = ref(0);
    let tableData = ref([]);
    let userIds = ref([]);
    let dialogVisible = ref(false);
    let userDto = reactive({
        id: 0,
        username: '',
        name: '',
        password_cs: '',
        password: '',
        phone: '',
        roleName: '',
        createTime: '',
        updateTime: ''
    });
    let userDrawer = ref(false);
    let userId = ref(0);
    let roleIdList = ref([]);
    let roleList = ref([]);
    let checkAll = ref(false);
    let isIndeterminate = ref(false);
    const userDtoRef = ref();
    const passwordValidator = (rule, value:string, callback) => {
        if(value !== userDto.password_cs) return callback(new Error('两次输入的密码不一致'));
        callback();
     }
    const userRules = {
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        name: [{ required: true, message: "请输入用户昵称", trigger: "blur" }],
        password_cs: [
            { required: true, message: "请输入密码", trigger: "blur" },
            { min: 6, max: 20, message: "密码长度在6-20个字符之间", trigger: "blur" }
        ],
        password: [
            { required: true, message: "请输入确认密码", trigger: "blur" },
            { validator:passwordValidator, trigger: "blur" }
        ]
    };

    const getUserList = async () => {
        const res = await userApi.getUserList(currentPage.value, pageSize.value, username.value, name.value);
        if (res.code === 200) {
            tableData.value = res.data.records;
            total.value = res.data.total;
        }else ElMessage.error(res.message);
     }

    const resetUser = () => {
        username.value = '';
        name.value = '';
        currentPage.value = 1;
        pageSize.value = 10;
        tableData.value = [];
        total.value = 0;
        getUserList();
    }

    const handleSizeChange = (val:number) =>{
        pageSize.value = val;
        getUserList();
    }

    const handleCurrentChange = (val:number) =>{
        currentPage.value = val;
        getUserList();
    }

    const handleSelectionChange = (rows) => {
        userIds.value = rows.map(item => item.id);
    }

    const removeMoreUser = async () => {
        if(!userIds.value?.length) return ElMessage.warning('请至少选择一条需要删除的用户');
        const res = await userApi.deleteUserByIdList(userIds.value);
        if(res.code === 200){
            ElMessage.success('删除成功');
            getUserList();
        }else ElMessage.error(res.message);
    }

    const fpRole = async (id:number) => {
        userDrawer.value = true;
        userId.value = id;
        const res = await userApi.getUserById(id);
        if(res.code === 200){
            Object.assign(userDto, res.data)
        }else ElMessage.error(res.message);

        const resRole = await userApi.getRoleByUserId(id);
        if(resRole.code === 200){
            roleList.value = resRole.data.allRolesList || [];
            roleIdList.value = resRole.data.assignRoles.map(item => item.id);

            if(roleIdList.value.length === roleList.value.length) checkAll.value = true;
            else checkAll.value = false;
            isIndeterminate.value = (roleIdList.value.length > 0 && roleIdList.value.length < roleList.value.length);
         }else ElMessage.error(resRole.message);
    }

    const editUser = async (id:number) => {
        const res = await userApi.getUserById(id);
        if(res.code === 200){
            Object.assign(userDto, res.data)
            dialogVisible.value = true;
        }else ElMessage.error(res.message);
    }

    const confirmAdd = () => {
        userDtoRef.value.validate(async valid => {
            if(valid){
                if(userDto.id) userDto.updateTime = new Date().Format('yyyy-MM-dd hh:mm:ss');
                delete userDto?.password_cs;
                const res = await userApi[userDto.id?'updateUser':'addUser'](userDto);
                if(res.code === 200){
                    ElMessage.success('添加成功');
                    initReset();
                    getUserList();
                }else ElMessage.error(res.message);
            }
        });
    }

    const confirmDelete = async (id:number) => {
        const res = await userApi.deleteUserById(id);
        if(res.code === 200){
            ElMessage.success('删除成功');
            getUserList();
        }else ElMessage.error(res.message);
    }

    const initReset = () => {
        dialogVisible.value = false;
        userDto = reactive({
            id: '',
            username: '',
            name: '',
            password_cs: '',
            password: '',
            phone: '',
            roleName: '',
            createTime: '',
            updateTime: ''
        });
        userDtoRef.value.resetFields();
        nextTick(() => {
            Object.keys(userDto).forEach((key) => {
                userDtoRef.value.clearValidate(key);
            });
        });
    }

    const cancelDrawer = () => {
        userDrawer.value = false;
        userId.value = 0;
        roleIdList.value = [];
        userDto = reactive({
            id: '',
            username: '',
            name: '',
            password_cs: '',
            password: '',
            phone: '',
            roleName: '',
            createTime: '',
            updateTime: ''
        });
    }

    const confirmDrawer = async () => {
        const res = await userApi.updateRoleByUser({ roleIdList: roleIdList.value, userId: userId.value});
        if(res.code === 200){
            ElMessage.success('分配角色成功');
            cancelDrawer();
            getUserList();
        }else ElMessage.error(res.message);
    }

    const handleCheckAllChange = (val: boolean) => {
        roleIdList.value = val ? roleList.value.map(item=>item.id) : [];
        isIndeterminate.value = false
    }

    const handleCheckedCitiesChange = (value: string[]) => {
        const checkedCount = value.length
        checkAll.value = checkedCount === roleList.value.length
        isIndeterminate.value = checkedCount > 0 && checkedCount < roleList.value.length
    }

    onMounted(() => {
        getUserList();
    });
</script>

<style scoped lang="scss">
    :deep(.queryForm .el-form-item){
        margin-bottom: 0;
    }
    :deep(.roleList .el-form-item__content){
        display: initial !important;
    }

    .table {
        width: 100%;
        margin-top: 10px;
    }
    
    .pagination{
        display: flex;
        align-items: center;
        justify-content: center;       
        margin-top: 20px; 
    }
</style>